#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <pthread.h>
#include <functional>

namespace ThreadMouble
{
    //typedef std::function<void()> func_t;
    using func_t = std::function<void()>;

    class Thread
    {
        void Excute() // 让EXcute去执行任务
        {
            _isrunning = true;
            _func(); 
            _isrunning = false;
        }

    public:
        Thread(const std::string &name, func_t func) : _name(name), _func(func)
        {
            std::cout << _name << "create done" << std::endl;
        }
        // 如果routing任务是普通类内成员函数,第一个参数一点是this,pthread_create函数的条件满足不了,所以要修改程static静态成员函数
        static void *routing(void *args)
        {
            Thread *th = static_cast<Thread *>(args);
            // th->_func(th->_name);这样传参去执行太丑陋
            th->Excute();
            return nullptr;
        }
        bool start()
        {
            int n = pthread_create(&_tid, nullptr, routing, (void *)this); // 进程创建直接去执行routing任务
            if (n == 0)
                return true;
            else
                return false;
        }
        void stop()
        {
            if (_isrunning)
            {
                pthread_cancel(_tid);
                _isrunning = false;
            }
        }
        void join()
        {
            pthread_join(_tid, nullptr);
        }

        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isrunning;
        func_t _func;
    };
}